package com.example.demo.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import com.example.demo.entity.*;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.service.CustomerService;
import com.example.demo.util.PayUtil;
import com.example.demo.util.wx.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/transfer")
@Transactional
public class TransferController {

	@Autowired
	CustomerMapper customerMapper;

	@Autowired
	CustomerService customerService;

	private static final Logger LOG = Logger.getLogger(TransferController.class);

	private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 企业付款

	private static final String TRANSFERS_PAY_QUERY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo"; // 企业付款查询

	private static final String APP_ID = ConfigUtil.getProperty("wx.appid");

	private static final String MCH_ID = ConfigUtil.getProperty("wx.mchid");

	private static final String API_SECRET = ConfigUtil.getProperty("wx.api.secret");
	private static final String desc = "佣金转账";

	/**localhost:6080/transfer/pay?phone=18712882023&amount=101
	 * 企业向个人支付转账
	 */
	@PostMapping("/pay")
	public JsonResult transferPay(String phone,Integer amount) {

		Integer frozen = customerMapper.getFrozen(phone);
		LOG.info("[/transfer/pay]");
		Integer in = 0;
		Integer amount1=0;
		Map<String, String> parm = new HashMap<String, String>();
		//业务判断 openid是否有收款资格
		Logs logs = new Logs();
		JsonResult json = new JsonResult();
		if(frozen==1){
			json.setMessage("您由于违规操作，账户已被冻结");
			json.setSuccess(false);
			return json;
		}
		//是否是会员
		Integer member = customerMapper.getMember(phone);
		if(member==0){
			WorkTable workTable = customerMapper.getWorkTableNoMembers(phone);
			String  openid = customerMapper.getOpenId(phone);
			//查询钱包里的金额是否足够
			if(openid==null){
				json.setSuccess(false);
				json.setMessage("用户没有绑定微信 不能提现 请先绑定微信");
				return json;
			}
			Wallet wallet = customerMapper.getWallet(phone);

			//已提取现金
			Integer readyAmount = customerMapper.getReadyAmount(phone);
			//钱包金额大于提取金额
			if(wallet.getMoney()>=amount){
				//当前等级可提现金额
				if(wallet.getAmount()>=amount){
					if(readyAmount!=null){
						if(readyAmount>=100){
//							customerMapper.setFrozen(phone);
							json.setSuccess(false);
							json.setMessage("非认证用户不能提取好友奖励，请先认证");
							return json;
						}
					}else {
						if(amount>100){
//							customerMapper.setFrozen(phone);
							json.setSuccess(false);
							json.setMessage("非认证用户不能提取好友奖励，请先认证");
							return json;
						}
					}
					String  partner_trade_no = PayUtil.getTransferNo();
					String nonce_str = PayUtil.getNonceStr();
					Map<String, String> restmap = null;
					try {
						//更新钱包金额
						customerMapper.updateAWallet(phone,-amount);
						parm.put("amount", String.valueOf(amount)); //转账金额
						parm.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
						parm.put("desc",desc+amount/100+"元 " ); //企业付款描述信息
						parm.put("mch_appid", APP_ID); //公众账号appid
						parm.put("mchid", MCH_ID); //商户号
						parm.put("nonce_str", nonce_str); //随机字符串
						parm.put("openid", openid); //用户openid
						parm.put("partner_trade_no", partner_trade_no); //商户订单号
						parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
						parm.put("spbill_create_ip", "59.110.223.237"); //服务器Ip地址
						parm.put("sign", PayUtil.getSign(parm, API_SECRET));
						String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
						restmap = XmlUtil.xmlParse(restxml);
						//将转账信息存入log表
						logs.setLogsCode(partner_trade_no);
						LocalDateTime localDateTime =LocalDateTime.now();
						logs.setLogsTime(String.valueOf(localDateTime));
						logs.setPhone(phone);
						logs.setLogsContent(desc+(double)amount/100+"元");
						logs.setAmount(amount);
						logs.setLogsType("1");
						customerMapper.saveLogsNoMember(logs);
					} catch (Exception e) {
						LOG.error(e.getMessage(), e);
					}
					if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
						LOG.info("转账成功!!!");
						Map<String, String> transferMap = new HashMap<>();
						transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
						transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
						transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间
						transferMap.put("content",parm.get("desc"));
						LocalDateTime localDateTime = LocalDateTime.now();
						logs.setTimeSure(String.valueOf(localDateTime));
						logs.setIsSure(1);
						logs.setFalseBack(parm.get("desc"));
						customerMapper.updateLogs(logs);
						json.setData(transferMap);
						json.setSuccess(true);
					}else {
						if (CollectionUtil.isNotEmpty(restmap)) {
							LOG.info("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
						}
						LocalDateTime localDateTime = LocalDateTime.now();
						logs.setTimeSure(String.valueOf(localDateTime));
						logs.setIsSure(0);
						logs.setFalseBack(restmap.get("err_code") + ":" + restmap.get("err_code_des"));
						customerMapper.updateLogs(logs);
						customerMapper.updateAWallet(phone,amount);
						json.setSuccess(false);
						json.setMessage("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
					}
				}else {
					json.setSuccess(false);
					json.setMessage("当前等级提取金额最大值为"+wallet.getAmount()/100+"元");
				}
			}else {
				json.setSuccess(false);
				json.setMessage("钱包金额不足"+amount/100+"元，转账失败！！");
			}
			customerMapper.update(phone);
			return json;
		}
		Integer bn = (amount-1)/5000;
		in = bn+1;
		amount1 = amount - 100*(in);
		String  openid = customerMapper.getOpenId(phone);
		//查询钱包里的金额是否足够
		if(openid==null){
			json.setSuccess(false);
			json.setMessage("用户没有绑定微信 不能提现 请先绑定微信");
			return json;
		}
		Wallet wallet = customerMapper.getWallet(phone);
		if(wallet.getMoney()>=amount){
			///钱包金额大于提取金额
			if(wallet.getAmount()>=amount){
				String  partner_trade_no = PayUtil.getTransferNo();
				String nonce_str = PayUtil.getNonceStr();
				Map<String, String> restmap = null;
				BaseInfo baseInfo = customerMapper.getBaseInfo();
				if(amount>=baseInfo.getWithdrawals()){
					try {
						//更新钱包金额
						customerMapper.updateAWallet(phone,-amount);
						parm.put("amount", String.valueOf(amount1)); //转账金额
						parm.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
						parm.put("desc",desc+amount/100+"元,手续费"+in+"元" ); //企业付款描述信息
						parm.put("mch_appid", APP_ID); //公众账号appid
						parm.put("mchid", MCH_ID); //商户号
						parm.put("nonce_str", nonce_str); //随机字符串
						parm.put("openid", openid); //用户openid
						parm.put("partner_trade_no", partner_trade_no); //商户订单号
						parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
						parm.put("spbill_create_ip", "59.110.223.237"); //服务器Ip地址
						parm.put("sign", PayUtil.getSign(parm, API_SECRET));
						String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
						restmap = XmlUtil.xmlParse(restxml);
						//将转账信息存入log表
						logs.setLogsCode(partner_trade_no);
						LocalDateTime localDateTime =LocalDateTime.now();
						logs.setLogsTime(String.valueOf(localDateTime));
						logs.setPhone(phone);
						logs.setLogsContent(desc+(double)amount1/100+"元");
						logs.setAmount(amount1+(in)*100);
						logs.setLogsType("1");
						customerMapper.saveLogs(logs);
					} catch (Exception e) {
						LOG.error(e.getMessage(), e);
					}
					if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
						LOG.info("转账成功!!!");
						Map<String, String> transferMap = new HashMap<>();
						transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
						transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
						transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间
						transferMap.put("content",parm.get("desc"));
						LocalDateTime localDateTime = LocalDateTime.now();
						logs.setTimeSure(String.valueOf(localDateTime));
						logs.setIsSure(1);
						logs.setFalseBack(parm.get("desc"));
						customerMapper.updateLogs(logs);
						json.setData(transferMap);
						json.setSuccess(true);
					}else {
						if (CollectionUtil.isNotEmpty(restmap)) {
							LOG.info("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
						}
						LocalDateTime localDateTime = LocalDateTime.now();
						logs.setTimeSure(String.valueOf(localDateTime));
						logs.setIsSure(0);
						logs.setFalseBack(restmap.get("err_code") + ":" + restmap.get("err_code_des"));
						customerMapper.updateLogs(logs);
						customerMapper.updateAWallet(phone,amount);
						json.setSuccess(false);
						json.setMessage("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
					}
				}else {
					json.setSuccess(false);
					json.setMessage("提现最小金额不能低于"+baseInfo.getWithdrawals()/100+"元！");
				}
			}else {
				json.setSuccess(false);
				//查询下一等级可提现金额
				Integer n = customerMapper.getMoney(wallet.getMemberLevel()+1)/100;
				json.setMessage("当前等级提取金额最大值为"+wallet.getAmount()/100+"元，升级至"+(wallet.getMemberLevel()+1)+"级可提现"+n+"元");
			}
		}else {
			json.setSuccess(false);
			json.setMessage("钱包金额不足"+amount/100+"元，转账失败！！");
		}
		customerMapper.update(phone);
		return json;
	}



/**
 * 获取token接口
 * https://api.weixin.qq.com/cgi-bin/token?
 * grant_type=client_credential
 * &appid=wx209abb61a1ca312e
 * &secret=dc6d37977888d62f5aa7dc80eb6c0daa
 *
 * 1、获取code接口
 * https://open.weixin.qq.com/connect/oauth2/authorize?
 * appid=wx209abb61a1ca312e
 * &redirect_uri=http://www.zhulipingtai.com/earn
 * &response_type=code
 * &scope=snsapi_base
 * &state=123#wechat_redirect
 *
 * 获取openId接口
 * https://api.weixin.qq.com/sns/oauth2/access_token?
 * appid=wx209abb61a1ca312e
 * &secret=dc6d37977888d62f5aa7dc80eb6c0daa
 * &code=001beJs70tzm5K1cH7v70heZs70beJs-
 * &grant_type=authorization_code
 */

}